import axios from 'axios'
import storage from './storage'
import { warn } from './log'

/**
 * @param {String} url
 * @returns {String}
 */
const handleUrl = (url: string): string => {
  if (process.env.NODE_ENV === 'development') return url
  else {
    // console.log(url)
    // console.log(url.split('/baseApi')[1])
    if (url.indexOf('/baseApi') > -1) {
      let _url = 'http://localhost:8848/' + url.split('/baseApi')[1]
      return _url
    }
    if (url.indexOf('/adminApi') > -1) {
      return 'http://localhost:8849/' + url.split('/adminApi')[1]
    }
    if (url.indexOf('/fileApi') > -1) {
      return 'http://localhost:8850/' + url.split('/fileApi')[1]
    }
    if (url.indexOf('/searchApi') > -1) {
      return 'http://localhost:8851/' + url.split('/searchApi')[1]
    }
    if (url.indexOf('/officeApi') > -1) {
      return 'http://localhost:8852/' + url.split('/officeApi')[1]
    }
  }
  // return ''
  return url
}
const http = axios.create({ baseURL: '/' }) //baseURL='https://reqres.in'用于指定请求
// class Response {
//     constructor() {
//         this.status = new Number()
//         this.data = new Object()
//         this.message = new String()
//     }
// }
interface ResponseType<T> {
  code: number
  data: T
  message: string
}

/**
 * @param {Response} res
 * @returns {Object}
 */
http.interceptors.response.use((res) => {
  if (res.data.code != 0 && res.data.code != '0') {
    console.warn(res?.data?.message)
  }
  return res?.data
})

// class HandledResponse {
//     constructor() {
//         this.code = new Number()
//         this.data = new Object()
//         this.message = new String()
//     }
// }
/**
 * @param {HandledResponse} response
 * @returns {HandledResponse}
 */
const handleRes = (response: ResponseType<any> | any) => {
  // if(response?.code===400){
  //   alert("当前业务异常")
  //   return
  // }
  if (response?.code === 400) {
    warn('请求错误')
    // message.warning(response?.message)
    return response
  }
  if (response?.code === 401) {
    warn('请求错误')
    return response
  }
  if (response?.code === 402) {
    warn('当前用户未正常登录')
    return response
  }
  if (response?.code === 500) {
    warn('系统错误\n' + response.message + '\n' + response.data)
    return response
  }
  if (response?.code == 0) {
    return response
  } else {
    if (typeof response === 'string') return response
    else {
      warn('request error:')
      return response
    }

    // alert("系统异常，不符合规范，请检查网络链接是否正常")
  }
}

class HttpRequest {
  header = {
    token: ''
  }

  constructor() {
    this.header = {
      token: storage.get('token')
    }
  }

  /**
   *
   * @param {String} method
   * @param {String} url
   * @param {*} data
   * @param {*} params
   * @returns
   */
  request<T, E>(method: string, url: string, data: any, params: any): Promise<T> {
    // const that = this
    let _url = handleUrl(url)
    this.header = {
      token: storage.get('token')
    }
    return new Promise((resolve, reject) => {
      http({
        method: method,
        url: _url,
        headers: {
          token: storage.get('token') ? storage.get('token') : '123'
        },
        data: data,
        params: params
      })
        .then((res) => {
          resolve(handleRes(res))
        })
        .catch((res) => {
          if (res?.response?.status == 500) console.error('net disconnect')
          else console.log(res)
          reject(res)
        })
    })
  }

  /**
   *
   * @param {String} url
   * @param {*} params
   */
  get<T1, T2>(url: string, params: T2): Promise<T1> {
    return this.request<T1, T2>('GET', url, {}, params)
  }
  getByUrl<T1>(url: string): Promise<T1> {
    return this.request<T1, any>('GET', url, {}, {})
  }

  post<T1, T2>(url: string, data: T2): Promise<T1> {
    return this.request('POST', url, data, {})
  }

  put<T1, T2>(url: string, data: T2): Promise<T1> {
    return this.request('PUT', url, data, {})
  }

  delete<T1, T2>(url: string, params: T2): Promise<T1> {
    return this.request('DELETE', url, {}, params)
  }

  // ...
}

class AsynHttpRequest {
  header = {
    token: ''
  }

  constructor() {
    this.header = {
      token: storage.get('token')
    }
  }

  /**
   *
   * @param {String} method
   * @param {String} url
   * @param {*} data
   * @param {*} params
   * @returns
   */
  AsynRequest<T, E>(method: string, url: string, data: any, params: any): Promise<T> {
    const that = this
    let _url = handleUrl(url)
    return new Promise((resolve, reject) => {
      http({
        method: method,
        url: _url,
        headers: {
          token: storage.get('token') ? storage.get('token') : '123'
        },
        data: data,
        params: params
      })
        .then((res) => {
          resolve(handleRes(res))
        })
        .catch((res) => {
          if (res?.response?.status == 500) console.error('net disconnect')
          else console.log(res)
          reject(res)
        })
    })
  }

  /**
   *
   * @param {String} url
   * @param {*} params
   */
  get<T1, T2>(url: string, params: T2): Promise<T1> {
    return this.AsynRequest<T1, T2>('GET', url, {}, params)
  }

  post<T1, T2>(url: string, data: T2): Promise<T1> {
    return this.AsynRequest('POST', url, data, {})
  }

  put<T1, T2>(url: string, data: T2): Promise<T1> {
    return this.AsynRequest('PUT', url, data, {})
  }

  delete<T1, T2>(url: string, params: T2): Promise<T1> {
    return this.AsynRequest('DELETE', url, {}, params)
  }
}

const request = new HttpRequest()
export default request
